import axios from 'axios';

const httpUrl = "http://qgm1.fengjian123.com/service9501/";

export function showTips(context, content) {
	context.tipContent = content;
	context.tip = 1;
	setTimeout(() => {
		context.tip = 0;
	}, 1000);
}

export function updateCartToServer(router) {
	const cartUpdateTime = window.sessionStorage.getItem('cartUpdateTime');
	const nowTime = new Date().getTime();
	if (cartUpdateTime == null) {
		UpdateCart(router);
		sessionStorage.setItem('cartUpdateTime', nowTime + 300000);
	} else {
		if (nowTime > cartUpdateTime) {
			UpdateCart(router);
			sessionStorage.setItem('cartUpdateTime', nowTime + 300000);
		}
	}
}

function UpdateCart(router) {
	const sessionData = window.sessionStorage.getItem('users');
	if (sessionData == null) {
		router.push('/login');
		console.log("登录失效");
		return;
	}

	const userData = JSON.parse(sessionData);
	const cartData = JSON.parse(sessionStorage.getItem('cart_' + userData.id));
	// console.log(cartData);
	axios.post(httpUrl + 'shop/addCart', null, {
			headers: {
				'Authorization': 'Bearer ' + userData.token,
				'Content-Type': 'application/json',
			},
			params: {
				userId: userData.id,
				cartData: JSON.stringify(cartData),
			}
		})
		.then(res => {
			console.log(res.data.msg);
		})
		.catch(error => {
			console.error("登录失败，请检查网络", error);
		});
}